package com.shiguiwu.springmybatis.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description: 排序耗时计算代理类
 * @author: stone
 * @date: Created by 2021/3/15 23:01
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.algorithm.sort
 */
public class UseTimeProxy<T> implements InvocationHandler {

    private T sort;

    public UseTimeProxy(T sort) {
        this.sort = sort;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long start = System.currentTimeMillis();
        Object invoke = method.invoke(sort, args);
        long end = System.currentTimeMillis();
        System.out.println(sort.getClass().getName() + "=>执行该排序所耗时间：" + (end - start));
        System.out.println("============================================");
        return invoke;
    }

    public static <T> T  createProxy(T sort, Class<T> sortClass) {
        if (!sortClass.isAssignableFrom(sort.getClass())) {
            throw new RuntimeException("不是子类，不能用改代理对象");
        }
        return (T) Proxy.newProxyInstance(sort.getClass().getClassLoader(), sort.getClass().getInterfaces(), new UseTimeProxy(sort));
    }
}
